package com.nep.controller;

import com.nep.entity.AqiFeedback;
import com.nep.entity.GridMember;
import com.nep.io.FileIO;
import com.nep.service.AqiFeedbackService;
import com.nep.service.impl.AqiFeedbackServiceImpl;
import com.nep.util.JavafxUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.io.File;

public class NepmAqiInfoViewController implements Initializable {

    @FXML
    private TableView<AqiFeedback> txt_tableView;
    
    public static Stage primaryStage;
    private AqiFeedbackService aqiFeedbackService = new AqiFeedbackServiceImpl();

    public TableView<AqiFeedback> getTxt_tableView() {
        return txt_tableView;
    }

    public void setTxt_tableView(TableView<AqiFeedback> txt_tableView) {
        this.txt_tableView = txt_tableView;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        //初始化table 数据表
        TableColumn<AqiFeedback, Integer> afIdColumn = new TableColumn<>("编号");
        afIdColumn.setMinWidth(40);
        afIdColumn.setStyle("-fx-alignment: center;");	//居中
        afIdColumn.setCellValueFactory(new PropertyValueFactory<>("afId"));

        TableColumn<AqiFeedback, String> proviceNameColumn = new TableColumn<>("省区域");
        proviceNameColumn.setMinWidth(60);
        proviceNameColumn.setStyle("-fx-alignment: center;");	//居中
        proviceNameColumn.setCellValueFactory(new PropertyValueFactory<>("proviceName"));

        TableColumn<AqiFeedback, String> cityNameColumn = new TableColumn<>("市区域");
        cityNameColumn.setMinWidth(60);
        cityNameColumn.setStyle("-fx-alignment: center;");	//居中
        cityNameColumn.setCellValueFactory(new PropertyValueFactory<>("cityName"));

        TableColumn<AqiFeedback, String> estimateGradeColumn = new TableColumn<>("预估等级");
        estimateGradeColumn.setMinWidth(60);
        estimateGradeColumn.setStyle("-fx-alignment: center;");	//居中
        estimateGradeColumn.setCellValueFactory(new PropertyValueFactory<>("estimateGrade"));

        TableColumn<AqiFeedback, String> dateColumn = new TableColumn<>("反馈时间");
        dateColumn.setMinWidth(80);
        dateColumn.setStyle("-fx-alignment: center;");	//居中
        dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));

        TableColumn<AqiFeedback, String> afNameColumn = new TableColumn<>("反馈者");
        afNameColumn.setMinWidth(60);
        afNameColumn.setStyle("-fx-alignment: center;");	//居中
        afNameColumn.setCellValueFactory(new PropertyValueFactory<>("afName"));

        TableColumn<AqiFeedback, String> infoColumn = new TableColumn<>("反馈信息");
        infoColumn.setMinWidth(210);
        infoColumn.setCellValueFactory(new PropertyValueFactory<>("infomation"));

        // 添加操作列
        TableColumn<AqiFeedback, Void> actionColumn = new TableColumn<>("操作");
        actionColumn.setMinWidth(240);
        actionColumn.setPrefWidth(240);
        actionColumn.setStyle("-fx-alignment: center;");
        
        Callback<TableColumn<AqiFeedback, Void>, TableCell<AqiFeedback, Void>> cellFactory = new Callback<>() {
            @Override
            public TableCell<AqiFeedback, Void> call(final TableColumn<AqiFeedback, Void> param) {
                return new TableCell<>() {
                    private final ComboBox<String> comboBox = new ComboBox<>();
                    private final Button assignButton = new Button("指派");
                    private final HBox hbox = new HBox(5); // 5是组件之间的间距
                    
                    {
                        // 设置样式
                        hbox.getStyleClass().add("assign-container");
                        comboBox.getStyleClass().add("assign-combo-box");
                        assignButton.getStyleClass().add("assign-button");
                        
                        // 初始化网格员下拉框
                        loadGridMembers(comboBox);
                        comboBox.setPromptText("选择网格员");
                        
                        // 设置指派按钮动作
                        assignButton.setOnAction(event -> {
                            AqiFeedback feedback = getTableView().getItems().get(getIndex());
                            String selectedMember = comboBox.getValue();
                            if (selectedMember == null || selectedMember.isEmpty()) {
                                JavafxUtil.showAlert(primaryStage, "指派失败", "请选择网格员", "请选择要指派的网格员", "warn");
                                return;
                            }
                            
                            try {
                                aqiFeedbackService.assignGridMember(feedback.getAfId().toString(), selectedMember);
                                JavafxUtil.showAlert(primaryStage, "指派成功", "网格员指派成功", "网格员" + selectedMember + "已成功指派", "info");
                                refreshTableData();
                            } catch (Exception e) {
                                JavafxUtil.showAlert(primaryStage, "指派失败", "网格员指派失败", "请检查数据是否正确", "error");
                            }
                        });
                        
                        hbox.getChildren().addAll(comboBox, assignButton);
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(hbox);
                        }
                    }
                };
            }
        };
        
        actionColumn.setCellFactory(cellFactory);

        txt_tableView.getColumns().addAll(afIdColumn, proviceNameColumn, cityNameColumn, estimateGradeColumn,
                dateColumn, afNameColumn, infoColumn, actionColumn);
                
        // 设置表格样式
        txt_tableView.setStyle("-fx-font-size: 14px;");
        
        refreshTableData();
    }
    
    private void loadGridMembers(ComboBox<String> comboBox) {
        File file = new File("gridmember.txt");
        if (!file.exists() || file.length() == 0) {
            return;
        }
        
        try {
            List<GridMember> glist = (List<GridMember>) FileIO.readObject("gridmember.txt");
            if (glist != null) {
                for (GridMember gm : glist) {
                    if (gm != null && gm.getState() != null && gm.getState().equals("工作中")) {
                        comboBox.getItems().add(gm.getRealName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void refreshTableData() {
        ObservableList<AqiFeedback> data = FXCollections.observableArrayList();
        List<AqiFeedback> afList = (List<AqiFeedback>) FileIO.readObject("aqifeedback.txt");
        if (afList != null) {
            for (AqiFeedback afb : afList) {
                if (afb != null && afb.getState() != null && afb.getState().equals("未指派")) {
                    data.add(afb);
                }
            }
        }
        txt_tableView.setItems(data);
    }
}